package com.uenpay.im.fragment;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;

import com.qyx.android.database.DBTopMsgColumns;
import com.qyx.android.database.FriendDB;
import com.qyx.android.database.GroupTalkDbManager;
import com.qyx.android.database.TalkMsgManager;
import com.qyx.android.database.TopListMsgManager;
import com.qyx.android.entity.FriendEntity;
import com.qyx.android.entity.GroupTalkEntity;
import com.qyx.android.message.type.MenuMsgType;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.protocol.QyxTopMsg;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.chat.ActivityHandle;
import com.uenpay.im.ui.old.activity.company.CreateCompanyActivity;
import com.uenpay.im.ui.old.activity.contacts.SearchFriendsActivity;
import com.uenpay.im.ui.old.activity.group.ChooseCreateGroupTypeActivity;
import com.uenpay.im.ui.old.activity.group.SearchGroupsActivity;
import com.uenpay.im.adapter.TalkLongClickViewAdapter;
import com.uenpay.im.adapter.TopListMsgAdapter;
import com.uenpay.im.callback.FragmentCallBack;
import com.uenpay.im.callback.IPopupWindowListener;
import com.uenpay.im.configuration.ShareData;
import com.uenpay.im.entities.PopupEntity;
import com.uenpay.im.entities.TalkLongClickViewEntity;
import com.uenpay.im.view.MyPopupWindow;
import com.uenpay.im.weight.MyDialog;
import com.uenpay.im.zxing.CaptureActivity;

import java.util.ArrayList;

/**
 *
 * 会话列表 CopyRight:http://www.qiyunxin.com
 *
 * @author SL
 * @Create Date: 2014-12-7 下午1:36:44
 *
 */

public class TalkListFragment extends Fragment {

	private FragmentCallBack mFragmentCallBack;
	private TextView conn_status;
	protected TopListMsgManager topListMsgManager = new TopListMsgManager();
	private TalkMsgManager takeMsgManager = new TalkMsgManager();
	private MsgReceiver msgReceiver = null;
	protected ArrayList<QyxTopMsg> arrayList = new ArrayList<QyxTopMsg>();
	protected TopListMsgAdapter topListMsgAdapter;
	private boolean is_query = false;
	private View view;
	private ListView msg_lv;
	private MyPopupWindow myPopupWindow;
	private GroupTalkDbManager mGroupTalkDbManager = new GroupTalkDbManager();

	// private TopMsgDBManagement topMsgDBManagement = new TopMsgDBManagement();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		if (view == null) {
			view = inflater.inflate(R.layout.fragment_talk_list_layout, container, false);
			initView();
			initLisenter();
		}
		ViewGroup parent = (ViewGroup) view.getParent();
		if (parent != null) {
			parent.removeView(view);
		}

		return view;
	}

	private void initView() {
		conn_status = (TextView) view.findViewById(R.id.conn_status);
		msg_lv = (ListView) view.findViewById(R.id.talk_list);
		view.findViewById(R.id.back_layout).setVisibility(View.GONE);
		view.findViewById(R.id.title_right_iv_layout).setVisibility(View.VISIBLE);
		myPopupWindow = new MyPopupWindow(getActivity(), getPopData(), new IPopupWindowListener() {

			@Override
			public void itemClick(int index) {
				if (index == 1) {
					Intent intent = new Intent(getActivity(), ChooseCreateGroupTypeActivity.class);
					startActivity(intent);
				} else if (index == 2) {
					Intent intent = new Intent(getActivity(), SearchFriendsActivity.class);
					startActivity(intent);
				} /* else if (index == 3) {
					Intent intent = new Intent(getActivity(), SearchGroupsActivity.class);
					startActivity(intent);
				} */else if (index == 3) {
					Intent intent = new Intent(getActivity(), CaptureActivity.class);
					startActivity(intent);
				} else if (index == 5) {
					Intent intent = new Intent(getActivity(), CreateCompanyActivity.class);
					startActivity(intent);
				}
			}
		});
	}

	private ArrayList<PopupEntity> getPopData() {
		ArrayList<PopupEntity> arrayList = new ArrayList<PopupEntity>();
//		PopupEntity entity = new PopupEntity(R.drawable.icon_start_chat, R.string.start_group, 1);
//		PopupEntity entity1 = new PopupEntity(R.drawable.icon_add_friends, R.string.add_friends, 2);
//		PopupEntity entity2 = new PopupEntity(R.drawable.icon_search_group, R.string.search_groups, 3);
//		PopupEntity entity3 = new PopupEntity(R.drawable.icon_sweep_white, R.string.sweep, 4);
//		PopupEntity entity4 = new PopupEntity(R.drawable.icon_create_company, R.string.create_company, 5);
//		msg_list.add(entity);
//		msg_list.add(entity1);
//		msg_list.add(entity2);
//		msg_list.add(entity3);
//		msg_list.add(entity4);
		return arrayList;
	}

	private void initLisenter() {
		view.findViewById(R.id.title_right_iv_layout).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (myPopupWindow != null) {
					myPopupWindow.show(arg0);
				}
			}
		});

		msg_lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

				QyxTopMsg topMsg = (QyxTopMsg) parent.getAdapter().getItem(position);
				int count = topMsg.msg_count;

				ActivityHandle.startChat(getActivity(), topMsg.sessionModel.getSessionId(), topMsg.sessionModel.getSessionType(),
						topMsg.sessionModel.getOperationType(), topMsg.chat_name, count, null);

				if (topMsg.msg_count != 0) {
					topMsg.msg_count = 0;
					topListMsgAdapter.notifyDataSetChanged();
					UpdateTotalMsg(null);
					topListMsgManager.update(topMsg);
				}
				/** 修改@信息 **/
				if (topMsg.is_at == 1) {
					updateAtMsg(topMsg);
				}

			}

		});

		msg_lv.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
				deleteDialog((QyxTopMsg) parent.getAdapter().getItem(position));
				return true;
			}
		});
	}

	@Override
	public void onResume() {

		if (IMApplication.IS_REFRESH_TOP_MSG) {
			queryMsg(null);
		}

		if (msgReceiver == null) {
			IntentFilter filter = new IntentFilter();
			filter.addAction(BroadcastAction.GET_TALKDETAIL_ACTION);
			filter.addAction(BroadcastAction.TAKEING_MSG_TOP_MSG);
			filter.addAction(BroadcastAction.ACTION_CONN_STAUTS);
			filter.addAction(BroadcastAction.CLEAR_TALK_MSG_ACTION);
			filter.addAction(BroadcastAction.ACTION_WITHDRAW_MSG);
			filter.addAction(BroadcastAction.ACTION_REFRESH_AVATAR);
			filter.addAction(BroadcastAction.ACTION_CLEAR_MSG_COUNT);
			filter.addAction(BroadcastAction.ACTION_REFRESH_FRIEND_NAME);
			filter.addAction(BroadcastAction.DELETE_FRIEND_ACTION);

			msgReceiver = new MsgReceiver();
			getActivity().registerReceiver(msgReceiver, filter);
		}
		ShareData.getInstance().setCurPage(IMApplication.PAGE.PAGE_TALK);
		IMApplication.notification_sum = 0;
		NotificationManager mNotificationManager = (NotificationManager) IMApplication.getAppContext().getSystemService(
				Context.NOTIFICATION_SERVICE);
		mNotificationManager.cancel(0);

		super.onResume();
	}

	protected void queryMsg(final String action) {
		if (is_query) {
			return;
		}

		is_query = true;

		new Thread(new Runnable() {

			@Override
			public void run() {
				arrayList = topListMsgManager.query();
				Message msg = myHandler.obtainMessage();
				msg.what = 3;
				msg.obj = action;
				myHandler.sendMessage(msg);
			}
		}).start();

	}

	public class MsgReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(BroadcastAction.TAKEING_MSG_TOP_MSG) || action.equals(BroadcastAction.ACTION_WITHDRAW_MSG)) {
				queryMsg(BroadcastAction.TAKEING_MSG_TOP_MSG);
			} else if (intent.getAction().equals(BroadcastAction.GET_TALKDETAIL_ACTION)) {

				String status = intent.getStringExtra("status");
				if (status.equals("success")) {
					Message msg = myHandler.obtainMessage();
					msg.obj = intent.getStringExtra("name");
					msg.arg1 = intent.getIntExtra("chat_id", 0);
					msg.what = 0;
					myHandler.sendMessage(msg);
				}

			} else if (intent.getAction().equals(BroadcastAction.ACTION_CONN_STAUTS)) {
				int status_code = intent.getIntExtra("status_code", 0);
				Message msg = myHandler.obtainMessage();
				msg.arg1 = status_code;
				msg.what = 1;
				myHandler.sendMessage(msg);

			} else if (intent.getAction().equals(BroadcastAction.CLEAR_TALK_MSG_ACTION)
					|| intent.getAction().equals(BroadcastAction.DELETE_FRIEND_ACTION)) {
				Message msg = myHandler.obtainMessage();
				msg.what = 2;
				myHandler.sendMessage(msg);
			} else if (intent.getAction().equals(BroadcastAction.ACTION_CLEAR_MSG_COUNT)) {
				Message msg = myHandler.obtainMessage();
				msg.what = 2;
				myHandler.sendMessage(msg);
			} else if (intent.getAction().equals(BroadcastAction.ACTION_REFRESH_AVATAR)
					|| intent.getAction().equals(BroadcastAction.ACTION_REFRESH_FRIEND_NAME)) {
				queryMsg(null);
			}
		}
	}

	private Handler myHandler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message msg) {

			if (msg.what == 0) {
				topListMsgManager.updateName(Long.valueOf(msg.arg1), msg.obj + "", PacketType.GROUP);
				for (int i = 0; i < arrayList.size(); i++) {
					if (arrayList.get(i).from_cust_id == msg.arg1 && arrayList.get(i).sessionModel.getSessionType() == PacketType.GROUP) {
						arrayList.get(i).chat_name = msg.obj + "";
						break;
					}
				}

				if (topListMsgAdapter == null) {
					topListMsgAdapter = new TopListMsgAdapter(getActivity(), arrayList);
				}

				msg_lv.setAdapter(topListMsgAdapter);
				topListMsgAdapter.notifyDataSetChanged();
				UpdateTotalMsg(null);

			} else if (msg.what == 1) {
				if (msg.arg1 == 200) {
					conn_status.setVisibility(View.GONE);
					conn_status.setText(R.string.conn_status);
				} else if (msg.arg1 == 100) {
					conn_status.setText(R.string.recv_msg_status);
					conn_status.setVisibility(View.VISIBLE);
				} else {
					conn_status.setVisibility(View.VISIBLE);
				}
			} else if (msg.what == 2) {
				queryMsg(null);
			} else if (msg.what == 3) {
				if (topListMsgAdapter == null) {
					topListMsgAdapter = new TopListMsgAdapter(IMApplication.getAppContext(), arrayList);
					msg_lv.setAdapter(topListMsgAdapter);

				} else {
					topListMsgAdapter.setData(arrayList);
				}

				UpdateTotalMsg((String) msg.obj);
				is_query = false;
				IMApplication.IS_REFRESH_TOP_MSG = false;
			}

			return false;
		}
	});

	private void UpdateTotalMsg(String action) {
		// int sum = 0;
		// for (int i = 0; i < msg_list.size(); i++) {
		// if (msg_list.get(i).msg_count != 0) {
		// sum += msg_list.get(i).msg_count;
		// }
		// }
		// IMApplication.config.setUnreadChatMsgCount(sum);
		// mFragmentCallBack.updateMsgCount("add", sum);

		int sum = 0;
		for (int i = 0; i < arrayList.size(); i++) {
			if (arrayList.get(i).msg_count != 0) {
				if (arrayList.get(i).sessionModel.getSessionType() == PacketType.PERSONAL) {
					FriendEntity friendEntity = FriendDB.getFriend(arrayList.get(i).sessionModel.getSessionId() + "");
					if (friendEntity != null && friendEntity.is_remind == 0) {
						sum += arrayList.get(i).msg_count;
					}
				} else {
					GroupTalkEntity groupTalk = mGroupTalkDbManager.queryGroupByGroupId(arrayList.get(i).sessionModel.getSessionId());
					if (groupTalk != null && groupTalk.is_remind == 0) {
						sum += arrayList.get(i).msg_count;
					}
				}
			}
		}
		IMApplication.config.setUnreadChatMsgCount(sum);
		mFragmentCallBack.updateTabMsg(FragmentCallBack.TABTYPE.TAB_TALK_MSG, FragmentCallBack.REMINDTYPE.TAB_REMIND_NEW_MSG, sum);

	}

	private void deleteDialog(final QyxTopMsg msg) {
		TalkLongClickViewAdapter adapter = null;

		final MyDialog.Builder dlg = new MyDialog.Builder(getActivity());
		final ListView menus = new ListView(getActivity());
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		menus.setLayoutParams(params);
		adapter = new TalkLongClickViewAdapter(getActivity(), getLongClickContent(msg.msg_count));
		menus.setAdapter(adapter);

		dlg.setListView(menus);
		dlg.setMessage("");
		if (!TextUtils.isEmpty(msg.chat_name) && msg.sessionModel.getSessionType() == PacketType.PERSONAL) {
			dlg.setTitle(msg.chat_name);
		} else if (msg.sessionModel.getSessionType() == PacketType.GROUP) {
			dlg.setTitle(R.string.delete_dialog_msg_title);
		} else {
			dlg.setTitle(R.string.action_dialog_title);
		}
		dlg.create().show();
		menus.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				TalkLongClickViewEntity mTalkLongClickViewEntity = (TalkLongClickViewEntity) arg0.getAdapter().getItem(arg2);
				if (mTalkLongClickViewEntity != null) {
					if (mTalkLongClickViewEntity.type == MenuMsgType.DELETE) {
						new DeleteMsgTask(msg).execute();
					} else if (mTalkLongClickViewEntity.type == MenuMsgType.MARK_READ) {
						setMarkReadMsg(msg);
					} else if (mTalkLongClickViewEntity.type == MenuMsgType.MARK_UNREAD) {
						setMarkUnReadMsg(msg);
					}
				}
				dlg.getDialog().dismiss();
			}
		});

	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mFragmentCallBack = (FragmentCallBack) activity;
	}

	@Override
	public void onPause() {
		super.onPause();
		ShareData.getInstance().setCurPage(IMApplication.PAGE.PAGE_NULL);
	}

	@Override
	public void onDestroy() {
		if (msgReceiver != null) {
			getActivity().unregisterReceiver(msgReceiver);
		}
		super.onDestroy();
	}

	/**
	 * 删除消息
	 *
	 * @author SL
	 *
	 */
	private class DeleteMsgTask extends AsyncTask<Void, Void, Void> {
		private QyxTopMsg delMsg = null;

		public DeleteMsgTask(QyxTopMsg _DelMsg) {
			delMsg = _DelMsg;
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			if (delMsg != null) {
				topListMsgManager.deleteByMsg(delMsg.sessionModel.getSessionId(), delMsg.sessionModel.getSessionType());
				if (delMsg.sessionModel.getSessionType() == PacketType.GROUP) {
					takeMsgManager.deleteGroupAllMsgByGroupId(delMsg.sessionModel.getSessionId());
				} else if (delMsg.sessionModel.getSessionType() == PacketType.PERSONAL) {
					takeMsgManager.deleteMsgByFromCustIdAndToCustId(delMsg.sessionModel.getSessionId(),
							Long.valueOf(IMApplication.getCustId()));
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			arrayList.remove(delMsg);
			topListMsgAdapter.notifyDataSetChanged();
			UpdateTotalMsg(null);
		}
	}

	/**
	 *
	 * @param count
	 * @return
	 */
	private ArrayList<TalkLongClickViewEntity> getLongClickContent(int count) {
		ArrayList<TalkLongClickViewEntity> arrayList = new ArrayList<TalkLongClickViewEntity>();
		TalkLongClickViewEntity mTalkLongClickViewEntity = new TalkLongClickViewEntity(MenuMsgType.DELETE, R.string.delete_talk);
		if (count > 0) {
			TalkLongClickViewEntity mTalkLongClickViewEntity1 = new TalkLongClickViewEntity(MenuMsgType.MARK_READ, R.string.mark_read);
			arrayList.add(mTalkLongClickViewEntity1);
		} else {
			TalkLongClickViewEntity mTalkLongClickViewEntity1 = new TalkLongClickViewEntity(MenuMsgType.MARK_UNREAD, R.string.mark_unread);
			arrayList.add(mTalkLongClickViewEntity1);
		}
		arrayList.add(mTalkLongClickViewEntity);

		return arrayList;
	}

	/**
	 * 设置消息已读
	 *
	 * @param message
	 */
	private void setMarkReadMsg(QyxTopMsg message) {
		int row = topListMsgManager.updateTopMsgByField(message.sessionModel.getSessionId(), message.sessionModel.getSessionType(),
				DBTopMsgColumns.MSG_COUNT, "0");
		if (row > 0) {
			message.msg_count = 0;
			refreshMsgList(message);
		}
	}

	/**
	 * 设置消息未读
	 *
	 * @param message
	 */
	private void setMarkUnReadMsg(QyxTopMsg message) {
		int row = topListMsgManager.updateTopMsgByField(message.sessionModel.getSessionId(), message.sessionModel.getSessionType(),
				DBTopMsgColumns.MSG_COUNT, "1");
		if (row > 0) {
			message.msg_count = 1;
			refreshMsgList(message);
		}
	}

	private void refreshMsgList(QyxTopMsg message) {
		for (int i = 0, size = arrayList.size(); i < size; i++) {
			if (arrayList.get(i).msg_no.equals(message.msg_no)) {
				arrayList.get(i).msg_count = message.msg_count;
				break;
			}
		}

		if (topListMsgAdapter != null) {
			topListMsgAdapter.setData(arrayList);
			topListMsgAdapter.notifyDataSetChanged();
		}
		UpdateTotalMsg(null);
	}

	/**
	 * 修改@状态
	 *
	 * @param topMsg
	 */
	private void updateAtMsg(QyxTopMsg topMsg) {
		topListMsgManager.updateTopMsgByField(topMsg.sessionModel.getSessionId(), topMsg.sessionModel.getSessionType(),
				DBTopMsgColumns.IS_AT, 0 + "");
		for (int i = 0, size = arrayList.size(); i < size; i++) {
			if (arrayList.get(i).msg_no.equals(topMsg.msg_no)) {
				arrayList.get(i).is_at = 0;
				break;
			}
		}
		topListMsgAdapter.notifyDataSetChanged();
	}

	// private void qyxMsg2TopMsg(QyxMsg qyxMsg) {
	// boolean is_add = true;
	// final QyxTopMsg mQyxTopMsg = topMsgDBManagement.qyxMsg2QyxTopMsg(qyxMsg);
	// if (mQyxTopMsg != null) {
	// for (int i = 0, size = msg_list.size(); i < size; i++) {
	// if (mQyxTopMsg.sessionModel.getSessionId() ==
	// msg_list.get(i).sessionModel
	// .getSessionId()) {
	// // TODO 存在该条记录.
	// is_add = false;
	// }
	// }
	// }
	// }

}
